package com.mzp.XbShop.controller;

import com.mzp.XbShop.common.entity.Result;
import com.mzp.XbShop.common.entity.StatusCode;
import com.mzp.XbShop.common.util.RandomValidateCodeUtil;
import com.mzp.XbShop.pojo.User;
import com.mzp.XbShop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Properties;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    //跳转到登陆页面
    @RequestMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("login");
    }


    //注册
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        userService.add(user);
        return new Result(StatusCode.OK, true, "增加成功");
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);//不设置过期时间
            //调用工具类去生产验证码
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


    //登陆
    @PostMapping(value = "/login/{yzm}", headers = "Accept=application/json")
    public Result login(@RequestBody User user, HttpServletRequest request,HttpServletResponse response, @PathVariable String yzm) {
        //如果用户不为空
        //获取验证码
//        RandomValidateCodeUtil randomValidateCodeUtil = new RandomValidateCodeUtil();
//        String keyRandom = randomValidateCodeUtil.keyRandom();
//        System.out.println("从randomValidateCodeUtil获取的验证码为:" + keyRandom);
//
//        //测试前端是否能传来验证码
//        System.out.println("验证码" + yzm);
        //从seesion获取验证码
        String randomKey = (String) request.getSession().getAttribute("randomKey");

//        System.out.println("从cookies获取的验证码为:" + randomKey);
        if (user.getUsername() != null && !user.getUsername().equals("")) {
            User loginUser = userService.findByusername(user);

            if (loginUser != null) {
                if (encoder.matches(user.getPassword(), loginUser.getPassword()) && yzm.equals(randomKey)) {
                    request.getSession().setAttribute("userInfo", user.getUsername());
                    loginUser.setPassword("");
                    //1
                    if(user.getIsfree()){
                        Cookie cookie = new Cookie("userId", loginUser.getId()+"");
                        cookie.setPath("/");
                        cookie.setMaxAge(60*60*24*7);
                        response.addCookie(cookie);

                        //存一个域对象 方做拦截器使用
                    }else {
                        request.getSession().setMaxInactiveInterval(1800);
                        Cookie cookie = new Cookie("userId", loginUser.getId()+"");
                        cookie.setPath("/");
                        cookie.setMaxAge(60*60*24*7);
                        /*将cookie放入到响应对象中*/
                        response.addCookie(cookie);
                    }
                    return new Result(true, StatusCode.OK, "登陆成功", loginUser);
                } else {
                    return new Result(true, StatusCode.USER_PASSWORD_ERROR, "密码或是验证码错误");
                }
            } else {
                return new Result(false, StatusCode.Empty, "没有当前用户");
            }
        } else {
            return new Result(false, StatusCode.Empty, "请输入用户名");
        }
    }



    /**
     * 通过姓名检测一个对象
     * 如果返回数据为null  表示可以注册 否则
     *
     * @param user
     * @return
     */
    @PostMapping("/checkUserName")
    public Result checkUserName(@RequestBody User user) {
        User byusername = userService.findByusername(user);
        if (byusername == null || byusername.equals("")) {
            return new Result(false, StatusCode.Empty, "可以注册", byusername);
        }
        return new Result(true, StatusCode.OK, "姓名重复", byusername);
    }

    /**
     * 通过邮箱检测一个对象
     * 如果返回数据为null  表示可以注册 否则
     *
     * @param user
     * @return
     */
    @PostMapping("/checkEmail")
    public Result checkEmail(@RequestBody User user) {
        User byusername = userService.findByEamil(user);
        if (byusername == null || byusername.equals("")) {
            return new Result(false, StatusCode.Empty, "邮箱可以注册", byusername);
        }
        return new Result(true, StatusCode.OK, "邮箱重复");
    }


    /**
     * 发送邮箱
     *
     * @param email
     * @param request
     * @return
     * @throws MessagingException
     */
    @GetMapping("/sendMail/{email}")
    public Result sendMail(@PathVariable String email, HttpServletRequest request) throws MessagingException {
        String num = userService.sendMail(email);
        System.out.println("验证码为:" + "----------" + num);
        if (num != null) {
            return new Result(true, StatusCode.OK, "发送成功", num);
        }
        return new Result(false, StatusCode.ERROR, "发送失败");
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.update(user);
        return new Result(StatusCode.OK, true, "修改成功");
    }

    /**
     * 通过id查询信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.OK, true, "查询成功", userService.findById(id));
    }

    /**
     * 通过id修改
     */

    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public Result updateUser(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.updateUser(user);
        return new Result(StatusCode.OK, true, "修改成功");
    }

    /**
     * 通过id修改 只修改密码
     */
    @RequestMapping(value = "/updatePassword/{id}", method = RequestMethod.PUT)
    public Result updatePassword(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.updatePassword(user);
        return new Result(StatusCode.OK, true, "修改成功");
    }

    /**
     *微信登陆处理回调
     * @throws Exception
     */
    @RequestMapping(value = "/loginByWechat",method = RequestMethod.GET)
    public Result wx_login() throws Exception {
        //加载配置文件
        Properties pro = new Properties();
        pro.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
        String appid = pro.getProperty("wx.AppID");
        //微信授权成功后的回调地址
        String redirect_uri = pro.getProperty("wx.redirect_uri");

        String url = "https://open.weixin.qq.com/connect/qrconnect?response_type=code"+
                "&appid=" + appid +
                "&redirect_uri=" + URLEncoder.encode(redirect_uri) +
                "&scope=snsapi_login";

        // 重定向到微信登录指定的地址进行微信登录授权,授权成功后返回code
        return new Result(true,StatusCode.OK,"成工",url);

    }

}
